﻿using MediatR;
using Microsoft.Identity.Client.Extensions.Msal;
using System.IdentityModel.Tokens.Jwt;
using W.Warehouse.Api.Application.Command.StorageCommand;
using W.Warehouse.Domain;
using W.Warehouse.Repository.Impl;
using W.Warehouse.Repository.Interface;

namespace W.Warehouse.Api.Application.CommandHandlder.StorageCommandHandlder
{
    public class StorageDelectCommandHandlder : IRequestHandler<StorageDelectCommand, ApiResult<int>>
    {
        private readonly ILogger<StorageDelectCommandHandlder> _logger;
        private readonly IStorageRepository _storageRepository;
        private readonly IStorageProductsRepository _storageProductsRepository;
        public StorageDelectCommandHandlder(ILogger<StorageDelectCommandHandlder> logger, IStorageRepository storageRepository, IStorageProductsRepository storageProductsRepository)
        {
            _logger = logger;
            _storageRepository = storageRepository;
            _storageProductsRepository = storageProductsRepository;
        }
        public async Task<ApiResult<int>> Handle(StorageDelectCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var slist = await _storageRepository.GetAllAsync();
                var splist = await _storageProductsRepository.GetAllAsync();
                var list = (from a in slist
                            join b in splist
                            on a.StorageId equals b.StorageId
                            where b.StorageProductsId == request.storageProductsId && a.IsDelete == false && b.IsDelete == false
                            select b).FirstOrDefault();
                if (list != null)
                {
                    list.IsDelete = true;
                    list.DeleteTime = DateTime.Now;
                }
                _logger.LogInformation("删除入库管理成功");
                result.Code = await _storageProductsRepository.UpdateAsync(list);
            }
            catch (Exception el)
            {
                result.Code = -1;
                result.Message = el.Message;
                _logger.LogError(el, el.Message);
                //throw;
            }
            return result;
        }
    }
}
